package app

import (
	"bytes"
	"html/template"
	"net/http"

	"github.com/inconshreveable/log15"
	"github.com/sourcegraph/sourcegraph/cmd/frontend/globals"
)

var openSearchDescription = template.Must(template.New("").Parse(`
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  <ShortName>{{.SiteName}}</ShortName>
  <Description>Search {{.SiteName}}</Description>
  <InputEncoding>UTF-8</InputEncoding>
  <Image height="16" width="16"></Image>
  <Url type="text/html" method="GET" template="{{.SearchURL}}" />
</OpenSearchDescription>
`))

func openSearch(w http.ResponseWriter, r *http.Request) {
	type vars struct {
		SiteName  string
		BaseURL   string
		SearchURL string
	}
	externalURL := globals.ExternalURL()
	externalURLStr := externalURL.String()
	data := vars{
		BaseURL:   externalURLStr,
		SearchURL: externalURLStr + "/search?q={searchTerms}",
	}
	if externalURLStr == "https://sourcegraph.com" {
		data.SiteName = "Sourcegraph"
	} else {
		data.SiteName = "Sourcegraph (" + externalURL.Host + ")"
	}

	var buf bytes.Buffer
	if err := openSearchDescription.Execute(&buf, data); err != nil {
		log15.Error("Failed to execute OpenSearch template", "err", err)
		http.Error(w, "", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/xml")
	_, _ = buf.WriteTo(w)
}
